package com.neusoft.view;

import com.neusoft.db.DBManager;
import com.neusoft.db.JdbcTemplate;
import com.neusoft.mapping.EntityMapping;
import com.neusoft.mapping.MappingFactory;
import com.neusoft.model.User;

import java.sql.Connection;
import java.util.List;

public class TestJdbcTemplate {
    public static void main(String[] args) {
        //1. 连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //2. 操作数据库(insert update delete select)
         JdbcTemplate jdbcTemplate = JdbcTemplate.getInstance(); //单例
         jdbcTemplate.setConnection(conn); //需要将DBManager中的conn传递给JdbcTemplate类中的conn
         //int isRight = jdbcTemplate.update("insert into user(username,password) values(?,?)","tomcat","123456");
        //int isRight = jdbcTemplate.update("delete from user where id = ?", 6);
        //System.out.println(isRight);
        //查询
        //需要从工厂类MappingFactory中获取到UserMapping对象
        MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.USER_MAPPING);
        List<Object> list = jdbcTemplate.query("select * from user where username = ? and password=?",mapping,"fender","123456");
        for(int i = 0;i<list.size();i++){
            User user = (User) list.get(i);
            System.out.println(user.getId() + " "
                    + user.getUsername() + " " + user.getPassword());
        }
    }
}
